package com.navinfo.platform.trip.common.arithmetic;

import com.navinfo.platform.trip.common.arithmetic.data.CommonData;
import com.navinfo.platform.trip.common.arithmetic.data.InterCrossCity;
import com.navinfo.platform.trip.common.arithmetic.data.OuterStatisticData;
import com.navinfo.platform.trip.common.arithmetic.var.VarCrossCity;
import com.navinfo.platform.trip.common.arithmetic.manager.AbstractArithmetic;
import com.navinfo.platform.trip.common.util.ArithmeticUtils;
import org.apache.flink.shaded.guava18.com.google.common.base.Joiner;

import java.util.Set;

/**
 * 经过城市算法<br/>
 * 依赖里程油耗算法{@link Mileage}<br/>
 * 输出：统计<br/>
 */
public class CrossCity extends AbstractArithmetic<VarCrossCity> {

    @Override
    public void calculate() {
        logger.debug("进入经过城市算法.");
        VarCrossCity var = getObj();
        CommonData commonData = getCommonData();

        //根据经纬度获取区域编码
        Integer currentLc = ArithmeticUtils.getLc(commonData.getOriginalLat(), commonData.getOriginalLng(), drivingData.getTileLcMapping());
        if(currentLc != null){
            //加入城市编码去重列表
            var.getCityCodes().add(currentLc);

            //上一个城市为null，或者上个城市和当前城市不一致，加入城市详情
            InterCrossCity preCrossCity = var.getPreCrossCity();
            InterCrossCity currentCrossCity = currentCrossCity(commonData, currentLc);
            if(preCrossCity==null || (preCrossCity!=null && currentCrossCity.getLcid()!=preCrossCity.getLcid()) ){
                var.getCrossCitiesDetail().add(currentCrossCity);
            }

            var.setPreCrossCity(currentCrossCity);
        }

        logger.debug("离开经过城市算法.");
    }

    /**
     * 创建当前经过城市信息
     * @param commonData
     * @param currentLc
     */
    private InterCrossCity currentCrossCity(CommonData commonData, Integer currentLc) {
        InterCrossCity crossCity = new InterCrossCity();
        crossCity.setLcid(currentLc);
        crossCity.setStime((int)(commonData.getGpsTime()/1000L));
        crossCity.setLatitude(commonData.getLatitude());
        crossCity.setLongitude(commonData.getLongitude());
        crossCity.setMileage((int)commonData.getIntegralMileage());
        crossCity.setFuel((int)commonData.getIntegralFuel());
        return crossCity;
    }

    @Override
    public void collect(OuterStatisticData statisticDataOut) {
        VarCrossCity var = getObj();
        Set<Integer> cityCodes = var.getCityCodes();
        statisticDataOut.setCrossCities(cityCodes.size()>0 ? Joiner.on(",").join(cityCodes.iterator()) : "");

        statisticDataOut.setCrossCitiesDetail(var.getCrossCitiesDetail());
    }
}